<?php

namespace App\Http\Middleware;

use App\Cache\Project\ProjectCache;
use App\Exceptions\ApiException;
use Closure;
use Illuminate\Http\Request;
use Dingo\Api\Routing\Route;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;

class RequestMiddleware
{
    /**
     * Notes:注入请求id
     *
     * DateTime: 2023/8/19 16:16
     * Author: tzhe
     * @param $request
     * @param Closure $next
     * @return mixed
     * @throws
     */
    public function handle($request, Closure $next): mixed
    {
        $action = "";
        $route  = $this->getDingoRoute($request);
        if ($route) {
            $action = $route->action['uri'];
        }

        // 限制接口请求频率
        // 全局去除特殊字符、空格
        if ($request->isMethod('post')) {
            $params = $request->all();
            foreach ($params as $field => $value) {
                if (in_array($field, ['name', 'title', 'level']) && $action != "/api/commonLang/addLang" && $action != "/api/commonLang/editLang") {
                    $request->request->set($field, rm_special($value));
                }
            }
        }
//        if (!in_array(request()->getRequestUri(), config('api.un_auth_urls'))) {
//            $agent     = $_SERVER['HTTP_AUTHORIZATION'];
//
//            $projectId = ProjectCache::get(keywords_cache_key([user_id(), $agent]));
//
//            if (empty($projectId)) {
//                throw new ApiException('用户未绑定项目', 401);
//            }
//        }
        $requestId = config('api.request_prefix') . Str::uuid();
//        Log::withContext(['request-id' => $requestId]);
        return $next($request)->header('Request-Id', $requestId);
    }

    protected function getDingoRoute(Request $request)
    {
        return $request->route();
    }
}
